package homework1;

import java.io.*;
import java.util.LinkedList;

/**
 * CalculateData()
 * 
 * @data 2013.7.8
 * @declaration Using LinkedList to read data, and calculate the data's mean and
 *              Standard deviation in file
 *              
 * @author 121250185 
 * 
 * Listing Contents:
 * @method: main(String[] args)
 * 			,calculateStdDev(LinkedList<Double> data, double mean)
 * 			,calculateMean(LinkedList<Double> data, double mean)
 * 			,readFile(String path)
 */

public class CalculateData {

	static LinkedList<Double> data = null;
	static BufferedReader br = null;
	
	static int line = 0;
	static double mean = 0.0;

	public static void main(String[] args) {
		// Calculate Column 1
		data = readFile("data.txt");
		System.out.println(String.format("Column 1's mean: %.2f",
				(mean = calculateMean(data, mean))));
		System.out.println(String.format("Column 1's Std. Dev: %.2f",
				calculateStdDev(data, mean)));
		// initial
		line = 0;
		mean = 0.0;
		// Calculate Column 2
		data = readFile("data2.txt");
		System.out.println(String.format("Column 2's mean: %.2f",
				(mean = calculateMean(data, mean))));
		System.out.println(String.format("Column 2's Std. Dev: %.2f",
				calculateStdDev(data, mean)));
	}// end

	/**
	 * calculateStdDev(LinkedList<Double> data, double mean)
	 * 
	 * @declaration: Calculate the Standard deviation
	 * @param data,mean
	 * @return Standard deviation
	 */
	private static double calculateStdDev(LinkedList<Double> data, double mean) {
		double std = 0.0;
		for (double i : data) {
			std += (i - mean) * (i - mean);
		}
		std /= (line - 1);
		return Math.sqrt(std);
	}// end

	/**
	 * calculateMean(ArrayList<Double> data, double mean)
	 * 
	 * @declaration: Calculate the mean
	 * @param data,mean
	 * @return mean
	 */
	private static double calculateMean(LinkedList<Double> data, double mean) {
		for (double i : data) {
			mean += i;
		}
		return mean / data.size();
	}// end

	/**
	 * readFile(String path)
	 * 
	 * @declaration: read the data from file
	 * @param path
	 * @return 
	 */
	public static LinkedList<Double> readFile(String path) {
		LinkedList<Double> data = new LinkedList<Double>();
		String temp = "";
		try {
			br = new BufferedReader(new FileReader(path));
			while ((temp = br.readLine()) != null) {
				data.add(Double.parseDouble(temp));
				line++;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return data;
	}// end
}
